package cn.lili.controller.order;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.order.order.OrderTempService;
//import cn.lili.modules.order.order.SysConfig;
//import cn.lili.modules.order.order.SysService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.sms.impl.SmsUtilAliImplService;
import cn.lili.modules.system.entity.dos.Setting;
import cn.lili.modules.system.service.SettingService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 管理端,订单列表API
 *
 * @since 2020-02-25 14:10:16
 */
@RestController
@Api(tags = "管理端,会员地址API")
@RequestMapping("/manager/order")
@Slf4j
public class OrderController {
    @Autowired
    private OrderTempService orderService;

    @Autowired
    private OrderService orderServiceNew;

//    @Autowired
//    private SysService sysService;

    @Autowired
    private Api_java_demo api_java_demo;

    @Autowired
    private SmsUtilAliImplService smsUtilAliImplService;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SettingService settingService;

//    @ApiOperation(value = "获取系统常量配置")
//    @GetMapping("/getVal")
//    public ResultMessage<SysConfig> getByPage(String key) {
//
//        return ResultUtil.data(sysService.getSys(key));
//    }
//


    private String printFlag = "printFlag";
    private String sendMsg = "sendMsg";

    //    OrderStatusEnum
    @ApiOperation(value = "派送端订单列表")
    @GetMapping("/getOrderListBySender")
    public ResultMessage<IPage<Order>> getOrderListBySender(PageVO page) {

        IPage<Order> iPage = orderService.getOrderList(page, null);

        List<Order> list = iPage.getRecords();
        list.stream().forEach(e -> {

            Object flag = stringRedisTemplate.opsForHash().get(printFlag, e.getSn());
            if (flag != null) {
                e.setPrintFlag(true);
            }

            Object sendFlag = stringRedisTemplate.opsForHash().get(sendMsg, e.getSn());
            if (sendFlag != null) {
                e.setSendFlag(true);
            }
        });
        iPage.setRecords(list);

        return ResultUtil.data(iPage);
    }

    @ApiOperation(value = "派送端更新订单列表")
    @GetMapping("/updateOrderList")
    public ResultMessage updateOrderList(String sn, String status) {

//        orderService.updateOrder(sn, status);
        Order order = orderServiceNew.getBySn(sn);
        if (order == null) {
            throw new ServiceException(ResultCode.ORDER_NOT_EXIST);
        }
        //判定是否是待收货状态
        if (!order.getOrderStatus().equals(OrderStatusEnum.DELIVERED.name())) {
            throw new ServiceException(ResultCode.ORDER_DELIVERED_ERROR);
        }
        log.info("updateOrderList完成:{}", JSONObject.toJSONString(order));
        orderServiceNew.completeNew(sn);
        return ResultUtil.data(null);
    }




    @ApiOperation(value = "打印订单")
    @GetMapping("/printOrder")
    public ResultMessage printOrder(String orderSn, String printMachineSn) {

        try {

            if (StringUtils.isBlank(printMachineSn)) {
                printMachineSn = Api_java_demo.SN;
            }
            log.info("printOrder_orderSn:{}, printMachineSn:{}", orderSn, printMachineSn);
            String method1 = api_java_demo.printNew(printMachineSn, orderSn);//该接口只能是小票机使用,如购买的是标签机请使用下面方法2，调用打印
            System.out.println(method1);
            if (JSONObject.parseObject(method1).get("msg").equals("ok")) {
                log.info("打印成功，设置缓存");
                stringRedisTemplate.opsForHash().put(printFlag, orderSn, "1");
            }
            return ResultUtil.data(method1);
        } catch (Exception e) {
            log.error("打印失败", e);
        }

        return ResultUtil.data("打印失败，请重试");
    }


    @ApiOperation(value = "发送短信")
    @GetMapping("/sendSms")
    public ResultMessage sendSms(String orderSn) {

        try {

            String address = "北京顺义区旺泉街道西辛南区10号楼2门101";
            String mobile = "13683190085";
            try {
                Setting setting = settingService.get("ADDRESS_DETAIL");
                address = JSONObject.parseObject(setting.getSettingValue()).getString("address");
                mobile = JSONObject.parseObject(setting.getSettingValue()).getString("mobile");
            } catch (Exception e) {
                log.error("地址异常", e);
            }

            Order order = orderService.getOrderInfo(orderSn);
            Map<String, String> param = new HashMap<>();
            param.put("adress", address);
            param.put("phone", mobile);
            smsUtilAliImplService.sendSmsCode1("金牌榜lilishop", order.getConsigneeMobile(), param, "SMS_225115751");

            stringRedisTemplate.opsForHash().put(sendMsg, orderSn, "1");
            return ResultUtil.data(null);
        } catch (Exception e) {
            log.error("打印失败", e);
        }

        return ResultUtil.data("打印失败，请重试");
    }


//    // 用户领取记录表
//    @Autowired
//    private RedBagDrawUserService redBagDrawUserService;
//
//    // 分配红包表
//    @Autowired
//    private RedBagService redBagService;
//
//    @Transactional
//    public ResultMessage getRed(Long userId) {
//
//
//        // 根据用户id查询是否有领取记录
//       int result = redBagDrawUserService.getRedBag(userId);
//        if (result > 0) {
//            return new ResultMessage();
//        }
//
//        // 查询倒序并且未领取过红包
//        Double rmbs = redBagService.getSort();
//
//        if (CollectionUtils.isEmpty(rmbs)) {
//            return new ResultMessage();
//        }
//        redBagDrawUserService.insert(userId, rmbs);
//        redBagService.update(id, "1");
//
//
//
//        return new ResultMessage();
//    }
//


        public static void main(String[] args) {
          String temp = "abc123";


          Set<String> set = new TreeSet<>();
          Iterator iterator = set.iterator();

            while (iterator.hasNext()) {
                iterator.next();
            }
          StringBuffer buffer = new StringBuffer();
            for (int i = temp.length() - 1; i >= 0 ; i--) {
                buffer.append(temp.charAt(i));
//                System.out.println(temp.charAt(i));
            }
            System.out.println(buffer.toString());
        }

}
